package org.sbbs.security.webapp.action;

import org.sbbs.base.webapp.action.BaseMaintainAction;
import org.sbbs.security.model.Menu;
import org.sbbs.security.service.MenuManager;
import org.sbbs.security.service.UrlResourceManager;

public class MenuMaintainAction extends BaseMaintainAction<Menu, Long> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private MenuManager menuManager;
	private UrlResourceManager urlResourceManager;
	private Menu model;

	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}

	public void setUrlResourceManager(UrlResourceManager urlResourceManager) {
		this.urlResourceManager = urlResourceManager;
	}

	public Menu getModel() {
		return model;
	}

	public void setModel(Menu model) {
		this.model = model;
	}

	public String add() {
		try {
			this.model = new Menu();
			this.setEditTypeAdd();
			return SUCCESS;
		} catch (Exception e) {

			return this.ajaxReturn.error(getText("error.common", new String[] { e.getMessage() }));

		}
	}

	public String edit() {
		try {
			this.model = this.menuManager.find(this.getId());
			this.setEditTypeEdit();
			return SUCCESS;
		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.common", new String[] { e.getMessage() }));
		}
	}

	public String save() {
		try {
			this.menuManager.save(this.getModel());
			return this.ajaxReturn.success(getText((isNew()) ? "demoEntity.added" : "demoEntity.updated",
					"no msg key found,save successed."));

		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.saved", new String[] { e.getMessage() }));
		}
	}

	public String delete() {
		try {
			String[] sIds = this.getIds().split(",");

			Long[] lIds = new Long[sIds.length];
			for (int i = 0; i < sIds.length; i++) {
				lIds[i] = Long.parseLong(sIds[i]);
			}

			this.menuManager.removeByIds(lIds);

			return this.ajaxReturn.success(getText((isNew()) ? "demoEntity.deleted" : "demoEntity.updated",
					"no msg key found,save successed."));

		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.deleted", new String[] { e.getMessage() }));
		}

	}

	public String initMenuFromUrlResource() {
		try {
			//List urls = this.urlResourceManager.findAll();
			this.menuManager.initMenuFromUrlResource();
			this.menuManager.reBuildAllTree();
			return this.ajaxReturn.success(getText("menu.inited", "no msg key found,menu inited  successed."));

		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.common", new String[] { e.getMessage() }));
		}
	}

	public String rebuildMenuTree() {
		try {
			this.menuManager.reBuildAllTree();
			return this.ajaxReturn.success("rebuild nest set tree success.");
		} catch (Exception e) {
			return this.ajaxReturn.error(getText("error.common", new String[] { e.getMessage() }));
		}

	}
}
